<?php
/**
 * Created by PhpStorm
 * User: Jhinwy
 * Date: 6/18/24
 * Time: 1:47 PM
 */

namespace App\Services;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CorpSelfService
{

    const REDIS_CORP_WECHAT_SELF_ACCESS_TOKEN = 'corp_wechat_self_access_token';


    protected $corpId;
    protected $selfSecret;

    public $api = [];

    protected $headers = ['Content-Type' => 'application/json'];

    public function __construct()
    {
        $this->corpId     = env('CORP_WECHAT_CORP_ID', '');
        $this->selfSecret = env('CORP_WECHAT_SELF_SECRET', '');

        $this->api = config('corp_wechat');
    }


    /**
     * 获取应用token
     *
     * @return mixed|string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getAccessToken()
    {
        if ($accessToken = Cache::get(self::REDIS_CORP_WECHAT_SELF_ACCESS_TOKEN)) {

            return $accessToken;
        }

        try {
            $client   = new Client();
            $response = $client->request('GET', sprintf($this->api['self_access_token'], $this->corpId, $this->selfSecret));
            if ($response->getStatusCode() != 200) {
                throw new \Exception('请求失败！');
            }
            $contents = $response->getBody()->getContents();
            Log::info('获取自建应用Token信息：', [$contents]);
            $data        = json_decode($contents, true);
            $accessToken = $data['access_token'] ?? '';
            $expiresIn   = $data['expires_in'] ?? 0;
            if (!$accessToken || !$expiresIn) {
                throw new \Exception('应用token不存在');
            }
            Cache::put(self::REDIS_CORP_WECHAT_SELF_ACCESS_TOKEN, $accessToken, $expiresIn);

            return $accessToken;
        } catch (\Exception $exception) {
            Log::error('获取自建应用token失败：' . $exception->getMessage());

            return '';
        }
    }
}
